﻿using System;
using System.Collections;
using System.Collections.Generic;
using Jink.Protocol.Core.Headers;
using XenoGears.Reflection.Shortcuts;
using System.Linq;

namespace Jink.Protocol.Media.Http
{
    internal static class HttpHeadersHelper
    {
        private static readonly Dictionary<String, RequestHeader> _s2req;
        private static readonly Dictionary<RequestHeader, String> _req2s;
        private static readonly Dictionary<String, ResponseHeader> _s2resp;
        private static readonly Dictionary<ResponseHeader, String> _resp2s;

        static HttpHeadersHelper()
        {
            var t_req_hack = Type.GetType("System.Net.UnsafeNclNativeMethods+HttpApi+HTTP_REQUEST_HEADER_ID");
            var f_req_hack = t_req_hack.GetField("m_Hashtable", BF.All);
            var req_hack = (Hashtable)f_req_hack.GetValue(null);
            _s2req = req_hack.Cast<DictionaryEntry>().ToDictionary(kvp => (String)kvp.Key, kvp => (RequestHeader)(int)kvp.Value);
            _req2s = req_hack.Cast<DictionaryEntry>().ToDictionary(kvp => (RequestHeader)(int)kvp.Value, kvp => (String)kvp.Key);

            var t_resp_hack = Type.GetType("System.Net.UnsafeNclNativeMethods+HttpApi+HTTP_RESPONSE_HEADER_ID");
            var f_resp_hack = t_resp_hack.GetField("m_Hashtable", BF.All);
            var resp_hack = (Hashtable)f_resp_hack.GetValue(null);
            _s2resp = resp_hack.Cast<DictionaryEntry>().ToDictionary(kvp => (String)kvp.Key, kvp => (ResponseHeader)(int)kvp.Value);
            _resp2s = resp_hack.Cast<DictionaryEntry>().ToDictionary(kvp => (ResponseHeader)(int)kvp.Value, kvp => (String)kvp.Key);
        }

        public static String ToHttpHeader(this RequestHeader header)
        {
            return _req2s[header];
        }

        public static RequestHeader ToRequestHeader(this String s)
        {
            return _s2req[s];
        }

        public static String ToHttpHeader(this ResponseHeader header)
        {
            return _resp2s[header];
        }

        public static ResponseHeader ToResponseHeader(this String s)
        {
            return _s2resp[s];
        }
    }
}
